package com.jz.community.moduleshoppingguide.neighbor.ui.activity;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.neighbor.bean.BlogsListBean;
import com.jz.community.moduleshoppingguide.neighbor.bean.CircleMessageBean;
import com.jz.community.moduleshoppingguide.neighbor.presenter.NeighborCirclePresenter;
import com.jz.community.moduleshoppingguide.neighbor.task.CommentReplyTask;
import com.jz.community.moduleshoppingguide.neighbor.task.FavoriteTask;
import com.jz.community.moduleshoppingguide.neighbor.ui.NeighborCircleView;
import com.jz.community.moduleshoppingguide.neighbor.ui.adapter.RelCircleDynamicAdapter;
import com.jz.community.moduleshoppingguide.neighbor.ui.view.DialogInput;
import com.jz.community.moduleshoppingguide.neighbor.ui.view.NeighborHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

import butterknife.BindView;

public class NeighborCircleActivity extends BaseMvpActivity<NeighborCircleView.View, NeighborCirclePresenter> implements NeighborCircleView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, RelCircleDynamicAdapter.OnCircleItemClickListener {


    @BindView(R2.id.circle_dynamic_back)
    ImageView circleDynamicBack;
    @BindView(R2.id.circle_dynamic_title)
    TextView circleDynamicTitle;
    @BindView(R2.id.cf_dynamic_recyclerView)
    RecyclerView cfDynamicRecyclerView;
    @BindView(R2.id.cf_dynamic_refresh)
    SmartRefreshLayout cfDynamicRefresh;

    RelCircleDynamicAdapter adapter;
    DialogInput dialogInput;

    private int page = 0;
    private int size = 10;
    private String circleId = "";


    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_neighbor_circle;
    }

    @Override
    protected NeighborCirclePresenter createPresenter() {
        return new NeighborCirclePresenter(this);
    }

    @Override
    protected void initView() {
        circleDynamicTitle.setText("圈子动态");
        adapter = new RelCircleDynamicAdapter(new ArrayList<>());
        cfDynamicRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        cfDynamicRecyclerView.setAdapter(adapter);
        cfDynamicRefresh.setOnRefreshListener(this);
        cfDynamicRefresh.setEnableLoadMore(false);
        adapter.setOnLoadMoreListener(this, cfDynamicRecyclerView);
    }

    @Override
    protected void initDatas() {
        circleId = getIntent().getStringExtra("circle_id");
        String comLat = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lat;
        String comLon = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lon;
        mPresenter.initNeighborMsg(circleId, comLat, comLon);
        mPresenter.circleDynamic(circleId + "", page, size, AppConstants.ONREFRESH);
    }

    @Override
    protected void addListener() {
        circleDynamicBack.setOnClickListener(v -> finish());
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(() -> handleWindowChange());
    }

    @Override
    public void showCircleDynamic(BlogsListBean blogsListBean, int type) {
        adapter.loadMoreEnd();
        cfDynamicRefresh.finishRefresh();
        if (blogsListBean.get_embedded().getContent() != null && blogsListBean.get_embedded().getContent().size() > 0) {
            if (type == AppConstants.ONREFRESH) {
                adapter.setNewData(blogsListBean.get_embedded().getContent());
            } else {
                adapter.addData(blogsListBean.get_embedded().getContent());
            }
            adapter.setListener(this);
        }
    }

    @Override
    public void setNeighborMsgData(CircleMessageBean entity) {
        initHeadData(entity);
    }

    private void initHeadData(CircleMessageBean circleBean) {
        NeighborHead head = new NeighborHead(this, cfDynamicRecyclerView);
        head.setData(circleBean);
        adapter.addHeaderView(head.getHeadView(), 0);
    }

    @Override
    public void showError(String s) {
        adapter.loadMoreEnd();
        cfDynamicRefresh.finishRefresh();
    }


    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        page = 0;
        mPresenter.circleDynamic(circleId + "", page, size, AppConstants.ONREFRESH);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        mPresenter.circleDynamic(circleId + "", page, size, AppConstants.ONLOADMORE);
    }

    @Override
    public void onItemAddPraiseClick(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {
        new FavoriteTask(this, o -> {
            if (o != null) {
                BlogsListBean.EmbeddedBean.ContentBean.FavoriteBean favoriteBean = (BlogsListBean.EmbeddedBean.ContentBean.FavoriteBean) o;
                if (item.getFavorite() != null && item.getFavorite().size() > 0) {
                    int j = -1;
                    for (int i = 0; i < item.getFavorite().size(); i++) {
                        if (item.getFavorite().get(i).getUserId().equals(favoriteBean.getUserId())) {
                            j = i;
                            break;
                        }
                    }
                    if (j != -1) {
                        item.getFavorite().remove(item.getFavorite().get(j));
                    } else {
                        item.getFavorite().add(favoriteBean);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    item.getFavorite().add(favoriteBean);
                    adapter.notifyDataSetChanged();
                }
            }
        }).execute(item.getId() + "");
    }

    @Override
    public void onItemAddCommentClick(View v, int position, BlogsListBean.EmbeddedBean.ContentBean item) {
        int itemBottomY = getCoordinateY(v) + v.getHeight();
        dialogInput = new DialogInput(this);
        dialogInput.show();
        //输入框根据位置弹出
        v.postDelayed(() -> {
            RelativeLayout llCommentInput = dialogInput.getInputView();
            int y = getCoordinateY(llCommentInput);
            if (position == adapter.getData().size() - 1) {
                BlogsListBean.EmbeddedBean.ContentBean c = new BlogsListBean.EmbeddedBean.ContentBean();
                c.setType(0);
                adapter.getData().add(c);
                adapter.bottomHeight = llCommentInput.getHeight();
                adapter.notifyDataSetChanged();
            }
            //滑动 RecyclerView，是对应 item 底部和输入框顶部对齐
            cfDynamicRecyclerView.smoothScrollBy(0, itemBottomY - y);
        }, 300);
        //提交评论
        dialogInput.getCommentBtn().setOnClickListener(v1 -> {
            if (!TextUtils.isEmpty(dialogInput.getEditString())) {
                new CommentReplyTask(this, o -> {
                    if (o != null) {
                        BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean replyVosBean = (BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean) o;
                        item.getReplyVos().add(replyVosBean);
                        adapter.notifyDataSetChanged();
                        dialogInput.dismiss();
                    }
                }).execute(item.getId() + "", dialogInput.getEditString(), BaseSpUtils.getInstance().getUserBaseInfo(this).getNickname(), BaseSpUtils.getInstance().getUserBaseInfo(this).getUid() + "", "1");
            }
        });
    }

    @Override
    public void onItemPutCommentPosition(View v, int position, int rvPosition, BlogsListBean.EmbeddedBean.ContentBean item) {
        int itemBottomY = getCoordinateY(v) + v.getHeight();
        dialogInput = new DialogInput(this);
        dialogInput.show();
        //输入框根据位置弹出
        v.postDelayed(() -> {
            RelativeLayout llCommentInput = dialogInput.getInputView();
            int y = getCoordinateY(llCommentInput);
            if (rvPosition == adapter.getData().size() - 1) {
                BlogsListBean.EmbeddedBean.ContentBean c = new BlogsListBean.EmbeddedBean.ContentBean();
                c.setType(0);
                adapter.getData().add(c);
                adapter.bottomHeight = llCommentInput.getHeight();
                adapter.notifyDataSetChanged();
            }
            //滑动 RecyclerView，是对应 item 底部和输入框顶部对齐
            cfDynamicRecyclerView.smoothScrollBy(0, itemBottomY - y);
        }, 300);
        //提交评论
        String userId = BaseSpUtils.getInstance().getUserId(this) + "";
        if (!userId.equals(item.getReplyVos().get(position).getReUserId())) {
            dialogInput.getCommentBtn().setOnClickListener(v1 -> {
                if (!TextUtils.isEmpty(dialogInput.getEditString())) {
                    new CommentReplyTask(this, o -> {
                        if (o != null) {
                            BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean replyVosBean = (BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean) o;
                            item.getReplyVos().add(replyVosBean);
                            adapter.notifyDataSetChanged();
                            dialogInput.dismiss();
                        }
                    }).execute(item.getId() + "", dialogInput.getEditString(), item.getReplyVos().get(position).getReNickName(), item.getReplyVos().get(position).getReUserId() + "", "1");
                }
            });
        } else {
            WpToast.l(this, "自己不能给自己回复!");
        }
    }

    @Override
    public void onItemClickListener(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {

    }

    @Override
    public void onItemClickHeadImage(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {

    }

    private int getCoordinateY(View view) {
        int[] coordinate = new int[2];
        view.getLocationOnScreen(coordinate);
        return coordinate[1];
    }

    private void handleWindowChange() {
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int displayHeight = rect.bottom - rect.top;
        int totalHeight = getWindow().getDecorView().getHeight();
        //显示内容的高度和屏幕高度比大于 0.8 时，dismiss dialog
        if ((float) displayHeight / totalHeight > 0.8) {
            //0.8只是一个大致的比例，可以修改
            if (null != dialogInput && dialogInput.isShowing()) {
                dialogInput.dismiss();
                //如果添加了空白 item ，移除空白 item
                if (adapter.getData().get(adapter.getData().size() - 1).getType() == 0) {
                    adapter.getData().remove(adapter.getData().size() - 1);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }
}
